package jsu.blogger.mapper;

import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.Set;

@Mapper
public interface UserFollowMapper {

    // 插入关注记录并传入关注时间，返回插入的行数
    @Insert("INSERT INTO user_focus (follower_id, followed_id, created_at) " +
            "VALUES (#{followerId}, #{followedId}, #{createdAt})")
    int insertFollow(@Param("followerId") Long followerId,
                     @Param("followedId") Long followedId,
                     @Param("createdAt") LocalDateTime createdAt);
    // 删除关注记录
    @Delete("DELETE FROM user_focus WHERE follower_id = #{followerId} AND followed_id = #{followedId}")
    int deleteFollow(@Param("followerId") Long followerId, @Param("followedId") Long followedId);
    // 查询用户的关注列表（关注了哪些用户）
    @Select("SELECT followed_id FROM user_focus WHERE follower_id = #{userId}")
    Set<Long> getUserFollowList(@Param("userId") Long userId);

    // 查询用户的粉丝列表（哪些用户关注了该用户）
    @Select("SELECT follower_id FROM user_focus WHERE followed_id = #{userId}")
    Set<Long> getUserFollowersList(@Param("userId") Long userId);

    // 增加用户的关注量
    @Update("UPDATE user_stats SET following_count = following_count + 1 WHERE user_id = #{userId}")
    int increaseFollowCount(@Param("userId") Long userId);

    // 增加用户的粉丝量
    @Update("UPDATE user_stats SET followers_count = followers_count + 1 WHERE user_id = #{userId}")
    int increaseFollowersCount(@Param("userId") Long userId);

    // 减少粉丝量：只有在粉丝量大于 0 时才执行减少操作
    @Update("UPDATE user_stats SET followers_count = followers_count - 1 WHERE user_id = #{userId} AND followers_count > 0")
    int decreaseFollowersCount(@Param("userId") Long userId);

    // 减少关注量：只有在关注量大于 0 时才执行减少操作
    @Update("UPDATE user_stats SET following_count = following_count - 1 WHERE user_id = #{userId} AND following_count > 0")
    int decreaseFollowCount(@Param("userId") Long userId);

}
